<template>
    <div class="home">
        <div class="box">
            <div class="top-wrap">
                <div class="top-fixed-tip">
                    <div class="top-fixed-tip-inner">
                        <div class="curent-user">
                            当前画家：<span>{{current_user}}</span>
                        </div>
                        <div class="problem"
                             v-if="!is_self_draw">
                            提示：({{problemData.problem.length + '个字)' + problemData.problem_tip}}
                        </div>
                        <div class="problem"
                             v-if="is_self_draw">
                            题目：{{problemData.problem}}
                        </div>
                        <div class="count-down">{{count_down}}S</div>
                    </div>
                </div>

                <canvas disable-scroll="true"
                        canvas-id="firstCanvas"
                        @touchstart="start"
                        @touchmove="move"
                        @touchend="end"
                        id="firstCanvas"></canvas>
                <div class="translate-tip"
                     :id="show_translate ? 'translate-tip' : ''">
                    {{translateTip}}
                </div>
                <operation :house_id="house_id"
                           :drawing_useing="drawing_useing"
                           @revoke_one="revoke_one"
                           @reserve="reserve" />
            </div>
            <div class="bottom-wrap">
                <div class="soso-house">
                    <div class="house_id">(房号：{{house_id}})</div>
                    <input class="house-num"
                           placeholder="输入答案"
                           v-model="answer_val" />
                    <div class="soso-num"
                         @click="go">抢答</div>
                </div>
                <div class="all-user">
                    <div v-for="(item,key) in members"
                         :key="key"
                         class="single-user">
                        <div class="info-box "
                             :class="item.m_status == 2 ? 'active':''">
                            <div class="mask"></div>
                            <div class="user-name">{{item.name}}</div>
                            <img :src="item.avatarUrl"
                                 class="user" />
                        </div>
                        <span class="score">{{item.score}}</span>
                    </div>
                </div>
            </div>
        </div>
        <cover-view :class=" is_self_draw ? '' : 'canvas-mask'"></cover-view>
        <cover-view :class=" is_global_mask ? 'global-mask' : ''"></cover-view>
        <rankingsModel :show_rankings_model="show_rankings_model"
                       :rank_members="rank_members"
                       @close_model="close_model" />
        <statisticsModel :show_statistics_model="show_statistics_model"
                         :problemData="problemData"
                         :members="members"
                         :count_down="count_down"
                         @close_model="close_model" />
        <!-- <div class="container"
            v-if="spinShow">
            <i-spin fix></i-spin>
        </div> -->
        <i-message id="message" />
    </div>
</template>

<script>
import store from '../../store';
import { getCurrentPageParams, getCurrentPageUrl } from '../../utils';
import rankingsModel from './dialog/rankings-model'
import statisticsModel from './dialog/statistics-model'
import operation from './components/operation'
const { $Message } = require('../../../static/iview/base/index');
export default {
    components: {
        rankingsModel,
        statisticsModel,
        operation
    },
    data() {
        return {
            stepsId: 0,
            show_translate: false, // 是否展示横幅动画
            show_statistics_model: false, // 是否展示统计分数
            show_rankings_model: false, // 是否展示排名
            is_global_mask: false, // 全屏遮罩层
            translateTip: '',
            house_id: '',
            house_status: '', // 0准备1开始,2计分中，3已结束4一人画完休息一会
            rank_members: [],
            members: {},
            count_down: 0, // 倒计时
            is_self_draw: false, // 当前是否是自己在作画
            current_user: '欢迎进入', // 当前作画者
            problemData: {
                problem: '',
                problem_id: 0,
                problem_tip: ''
            },
            drawing_useing: {
                drawing_color: '#202020', // 正在使用的颜色
                drawing_width: 5, // 正在使用的线条宽度
            },
        };
    },
    //wsOpenSuccess: false, // ws是否注册监听了事件
    context: {},
    startX: 0, // 保存X坐标轴变量
    startY: 0, // 保存Y坐标轴变量
    stepsId: 0,
    steps: [],
    statistics_timerId: '', // 统计时的10秒
    ping_timerId: '', // 心跳
    computed: {
        G() {
            return store.state.globalData;
        },
        socketOpen() {
            return store.state.globalData.WS.socketOpen
        }
    },
    watch: {
        socketOpen(newV) {
            const url = getCurrentPageUrl();
            if (url === 'pages/ongoing/main') {
                // !this.wsOpenSuccess && 
                if (newV) {
                    // 只需执行一次，防止
                    // this.wsOpenSuccess = true;
                    this.initWs()
                }
            }
        }
    },
    methods: {
        // 撤销一步
        revoke_one() {
            store.dispatch('sendSocketMessage', {
                type: 'draw_revoke',
                data: {
                    openid: this.G.openid,
                    house_id: this.house_id,
                    type: 2
                }
            });
        },
        // 清空canvas
        reserve() {
            wx.drawCanvas({
                canvasId: 'firstCanvas',
                reserve: false,
                actions: this.context.getActions() // 获取绘图动作数组
            });
            store.dispatch('sendSocketMessage', {
                type: 'draw_revoke',
                data: {
                    openid: this.G.openid,
                    house_id: this.house_id,
                    type: 1
                }
            });
        },
        handleChange({ target }) {
            this.current = target.key;
        },
        // 关闭弹窗按钮
        close_model() {
            this.show_statistics_model = false;
            this.is_global_mask = false;
            this.show_rankings_model = false;
        },

        start(e) {
            this.steps = [];
            // this.startX = e.changedTouches[0].x;
            // this.startY = e.changedTouches[0].y;
            this.startX = e.x;
            this.startY = e.y;
            if (!this.context) {
                this.context = wx.createCanvasContext('firstCanvas');
            }
            this.context.setStrokeStyle(this.drawing_useing.drawing_color);
            this.context.setLineWidth(this.drawing_useing.drawing_width);
            this.context.setLineCap('round'); // 让线条圆润
            this.context.beginPath();
        },
        move(e) {
            var startX1 = e.x;
            var startY1 = e.y;
            this.steps.push({
                id: this.stepsId++,
                start: [this.startX, this.startY],
                end: [startX1, startY1]
            });
            this.context.moveTo(this.startX, this.startY);
            this.context.lineTo(startX1, startY1);
            this.context.stroke();

            this.startX = startX1;
            this.startY = startY1;

            // 只是一个记录方法调用的容器，用于生成记录绘制行为的actions数组。context跟不存在对应关系，一个context生成画布的绘制动作数组可以应用于多个
            this.context.draw(true);
            // wx.drawCanvas({
            //   canvasId: 'firstCanvas',
            //   reserve: true,
            //   actions: this.context.getActions() // 获取绘图动作数组
            // })
        },

        end(e) {
            if (this.is_self_draw) {
                store.dispatch('sendSocketMessage', {
                    type: 'draw_steps',
                    data: {
                        steps: this.steps,
                        color: this.drawing_useing.drawing_color,
                        width: this.drawing_useing.drawing_width,
                        openid: this.G.openid,
                        house_id: this.house_id
                    }
                });
            }
        },

        // 播放横幅动画
        paly_animation(text) {
            this.show_translate = true;
            this.translateTip = text;

            setTimeout(() => {
                this.show_translate = false;
            }, 6 * 1000);
        },
        // 抢答
        go() {
            if (this.is_self_draw) {
                $Message({
                    content: '调皮了啊，自己不能答',
                    type: 'error',
                    duration: 2 // 持续的时间
                });
                return;
            }
            if (this.answer_val === '') {
                return;
            }
            let is_right = false;
            let score = 0;
            if (this.answer_val === this.problemData.problem) {
                $Message({
                    content: '答对了',
                    type: 'success',
                    duration: 2 // 持续的时间
                });
                is_right = true;
                score = 3;
            }
            // 发送答案给后台
            store.dispatch('sendSocketMessage', {
                type: 'answer',
                data: {
                    is_right: is_right,
                    answer: this.answer_val,
                    score: score,
                    house_id: this.house_id,
                    openid: this.G.openid,
                    name: this.G.userInfo.nickName
                }
            });

            this.answer_val = '';
        },
        input_answer(e) {
            // var val = e.detail.value;
            // this.setData({
            //   answer_val: val
            // });
        },
        // 初始进入页面获取房间信息
        get_house_info() {
            store.dispatch('sendSocketMessage', {
                type: 'get_begin_house_info',
                data: {
                    house_id: this.house_id,
                    openid: this.G.openid
                }
            });
        },
        // 渲染ws推送过来的作画数据
        render_draw_steps(data, reserve = true) {
            if (!this.context) {
                this.context = wx.createCanvasContext('firstCanvas');
            }
            this.context.beginPath();
            this.context.setStrokeStyle(data.color);
            this.context.setLineWidth(data.width);
            this.context.setLineCap('round'); // 让线条圆润
            data.steps.forEach(value => {
                this.context.moveTo(value.start[0], value.start[1]);
                this.context.lineTo(value.end[0], value.end[1]);
                this.context.stroke();
            });
            this.context.draw(reserve);
            // wx.drawCanvas({
            //   canvasId: 'firstCanvas',
            //   reserve: true,
            //   actions: this.context.getActions() // 获取绘图动作数组
            // })
        },
        // 处理ws推送的作画倒计时
        draw_countdown(data) {
            if (data !== 0) {
                this.count_down = data;

                clearInterval(this.statistics_timerId);
            } else if (data === 0) {
                wx.showLoading({
                    title: '时间到稍等...',
                    mask: true
                });
                let i = 10;
                this.statistics_timerId = setInterval(() => {
                    if (i === 0) {
                        clearInterval(this.statistics_timerId);
                        return;
                    }
                    this.count_down = '休息' + i;

                    i--;
                }, 1000);
            }
        },
        // 开始作画前的准备：immediately:立刻
        immediately_bengin(data) {
            wx.hideLoading();
            this.members = data.members;
            this.current_user = data.current_user;
            this.problemData = data.problemData;
            this.show_statistics_model = false;
            this.show_rankings_model = false;
            this.is_global_mask = false;

            if (this.context) {
                // 清空上组绘画数据
                wx.drawCanvas({
                    canvasId: 'firstCanvas',
                    reserve: false,
                    actions: this.context.getActions() // 获取绘图动作数组
                });
            }
            

            if (this.statistics_timerId) {
                // 清除计分环节的倒计时器
                clearInterval(this.statistics_timerId);
            }
        },
        // 初次进入页面时获取搭配的房间所有信息
        house_all_info(data) {
            this.first_house_all_info = true;
            let is_self_draw = false;
            let current_user = '';
            const members = data.members;
            if (data.status === 1) {
                // 只对房间作画状态做处理，计分和休息都可以等待新ws数据
                for (const openid in members) {
                    if (members[openid].m_status === 2) {
                        current_user = members[openid].name;
                        if (openid === this.G.openid) {
                            is_self_draw = true;
                        } else {
                            if (members[openid].draw_data.length > 0) {
                                // 因为全部重新渲染所以先全部清空
                                wx.drawCanvas({
                                    canvasId: 'firstCanvas',
                                    reserve: false,
                                    actions: this.context.getActions() // 获取绘图动作数组
                                });
                                members[openid].draw_data.forEach(value => {
                                    this.render_draw_steps(value);
                                });
                            }
                            is_self_draw = false;
                        }
                    }
                }
            } else if (data.status === 2) {
                $Message({
                    content: '正在计分中...',
                    type: 'warning',
                    duration: 2 // 持续的时间
                });
            }
            this.current_user = current_user;
            this.members = data.members;
            this.problemData = {
                problem: data.problem,
                problem_id: data.problem_id,
                problem_tip: data.problem_tip
            };
            this.house_status = data.status;
            this.is_self_draw = is_self_draw;
        },
        render_draw_revoke(data) {
            if (data.type === 1 || data.draw_data.length === 0) { // 清空
                if (this.context) {
                    // 清空上组绘画数据
                    wx.drawCanvas({
                        canvasId: 'firstCanvas',
                        reserve: false,
                        actions: this.context.getActions() // 获取绘图动作数组
                    });
                }
            } else if (data.type === 2) { // 撤销
                data.draw_data.forEach((value, index) => {
                    if (index === 0) {
                        this.render_draw_steps(value, false);
                    } else {
                        this.render_draw_steps(value, true);
                    }
                });
            }
        },
        // 初始化ws
        initWs() {
            wx.onSocketMessage(ret => {
                console.log('onSocketMessage-goning')
                const url = getCurrentPageUrl();
                if (url !== 'pages/ongoing/main') {
                    return;
                }
                if (!this.first_house_all_info && this.G.userInfo && this.G.openid) {
                    console.log('重新请求成员信息going');
                    // 写这个判断是因为经常进入页面户ws监听的还没来得及收到消息导致页面上没有头像
                    this.get_house_info();
                }
                const res = JSON.parse(ret.data);
                // 房间信息
                if (res.type === 'begin_house_info') {
                    this.house_all_info(res.data);
                }
                // 房间成员信息更新
                if (res.type === 'members') {
                    this.members = res.data;
                }
                // 轮到自己作画
                if (res.type === 'self_draw_problem') {
                    this.is_self_draw = true;
                    $Message({
                        content: '请准备作画，开始计时',
                        duration: 2 // 持续的时间
                    });
                    this.immediately_bengin(res.data);
                }
                // 轮到自己 猜
                if (res.type === 'ready_guess_problem') {
                    this.is_self_draw = false;
                    $Message({
                        content: '请准备猜题，开始计时',
                        duration: 2 // 持续的时间
                    });
                    this.immediately_bengin(res.data);
                }

                // 作画、猜画倒计时
                if (res.type === 'draw_countdown') {
                    this.draw_countdown(res.data);
                }
                // 服务器传来的作画人的笔画
                if (res.type === 'draw_steps') {
                    if (res.data) {
                        this.render_draw_steps(res.data);
                    }
                }
                if (res.type === 'other_answer') {
                    if (res.data) {
                        if (res.data.is_right) {
                            this.paly_animation(res.data.name + '答对喽');
                        } else {
                            this.paly_animation(res.data.name + '抢答了' + res.data.answer);
                        }
                    }
                }
                if (res.type === 'score') {
                    wx.hideLoading();
                    if (res.data) {
                        this.members = res.data;
                        this.show_statistics_model = true;
                        this.is_global_mask = true;
                    } else {
                        $Message({
                            content: '意外的score错误',
                            type: 'error',
                            duration: 2 // 持续的时间
                        });
                    }
                }
                // 游戏结束，展示排名
                if (res.type === 'game_over') {
                    wx.hideLoading();
                    if (res.data) {
                        this.rank_members = res.data;
                        this.show_statistics_model = false;
                        this.show_rankings_model = true;
                        this.is_global_mask = true;
                    }
                }
                // 再来一局错误
                if (res.type === 'onece_again_err') {
                    wx.hideLoading();
                    if (res.data) {
                        $Message({
                            content: res.data || '错误',
                            type: 'error',
                            duration: 2 // 持续的时间
                        });
                    } else {
                        $Message({
                            content: '意外的再来一局错误',
                            type: 'error',
                            duration: 2 // 持续的时间
                        });
                    }
                }

                if (res.type === 'house_err') {
                    // 直接退出
                    $Message({
                        content: res.data || '错误',
                        type: 'error',
                        duration: 3 // 持续的时间
                    });

                    setTimeout(() => {
                        wx.redirectTo({
                            url: `../index/main`
                        });
                    }, 3000);
                }

                if (res.type === 'draw_revoke') {
                    if (res.data) {
                        this.render_draw_revoke(res.data);
                    } else {
                        $Message({
                            content: '意外的撤回错误',
                            type: 'error',
                            duration: 2 // 持续的时间
                        });
                    }
                }
                console.log('websocket页面的消息onging：', res)
            });
            // 在本页面定期发送心跳
            this.ping_timerId = setInterval(() => {
                store.dispatch('sendSocketMessage', {
                    type: 'ping',
                    data: {
                        openid: this.G.openid,
                        house_id: this.house_id
                    }
                });
            }, 5000);
        }
    },
    onShow() {
        const urlParams = getCurrentPageParams();
        console.log('going+onShow' + 333);
        this.house_id = urlParams.house_id;
        // && !this.wsOpenSuccess
        if (this.socketOpen) {
            // 只需执行一次，防止ws还没开启就执行了注册监听事件
            //this.wsOpenSuccess = true;
            this.initWs();
        }
       
        this.get_house_info();
    },
    onUnload() {
        clearInterval(this.ping_timerId);
    },
    // 捕获 app error
    onError(err) {
        console.log('ongoing-error:' + err);
    }
};
</script>

<style scoped>
.box {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  overflow: hidden;
}
.top-fixed-tip {
  position: fixed;
  top: 0;
  height: 40px;
  right: 0;
  left: 0;
  z-index: 3;
  font-size: 13px;
}
.top-fixed-tip-inner {
  display: flex;
  line-height: 40px;
  background: #fff5ee;
}
.curent-user {
  flex: 1 1 130px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.problem {
  flex: 1 1 auto;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.count-down {
  flex: 0 0 25px;
  margin-left: 5px;
  font-size: 16px;
  color: red;
}
.top-wrap {
  height: 65%;
  position: relative;
}
.bottom-wrap {
  background: #fff5ee;
  height: 35%;
  overflow-y: auto;
}
.canvas-mask {
  position: absolute;
  top: 0;
  bottom: 35%;
  left: 0;
  right: 0;
  background-color: #fff;
  opacity: 0.1;
  z-index: 10;
}
#firstCanvas {
  width: 99%;
  box-sizing: border-box;
  height: 91%;
  margin: 0 auto;
  /* border: 1px solid red; */
}

.single-user {
  width: 80rpx;
  overflow: hidden;
  text-align: center;
  display: inline-block;
  margin: 5px;
}
.single-user .score {
  font-size: 12px;
  color: #e64340;
}
.single-user .info-box {
  width: 80rpx;
  height: 80rpx;
  box-sizing: border-box;
  position: relative;
  overflow: hidden;
  text-align: center;
}
.info-box.active {
  border: 3px solid red;
}

.info-box .user-name {
  position: absolute;
  width: 100%;
  z-index: 2;
  bottom: 2px;
  color: #fff;
  font-size: 10px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
.info-box .user {
  width: 100%;
  height: 100%;
}

.soso-house {
  width: 100%;
  text-align: center;
  margin: 20px auto;
}
.show_answer {
  text-align: center;
  font-size: 16px;
}
.house-num {
  border: 1px solid #e64340;
  width: 180px;
  height: 35px;
  line-height: 35px;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
  display: inline-block;
  vertical-align: middle;
}
.soso-num {
  width: 60px;
  height: 37px;
  background-color: #e64340;
  color: #fff;
  text-align: center;
  line-height: 35px;
  display: inline-block;
  vertical-align: middle;
}
.house_id {
  line-height: 30px;
  font-size: 14px;
  margin-right: 10px;
  display: inline-block;
  vertical-align: middle;
}
.translate-tip {
  background: #018ee8;
  color: #fff;
  padding: 10px 20px;
  position: fixed;
  top: 30%;
  z-index: 99;
  opacity: 0;
  overflow: hidden;
  white-space: nowrap;
}
#translate-tip {
  animation: aa 5s;
}

@keyframes aa {
  0% {
    left: -320px;
    opacity: 1;
  }

  50% {
    left: 0px;
    opacity: 1;
  }
  95% {
    left: 315px;
    opacity: 1;
  }
  100% {
    left: 100%;
  }
}

.global-mask {
  position: fixed;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 20;
  background: #000;
  opacity: 0.5;
}
</style>
